package com.sikaryofficial.knowledge.interceptor;

import org.slf4j.MDC;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.sikaryofficial.common.core.constant.Constants.TRACE_FLAG;

/**
 * 传递traceId
 */
@Component
public class Trace4RemoteInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String traceId = MDC.get(TRACE_FLAG);
        if (traceId != null) {
            httpRequest.getHeaders().add(TRACE_FLAG, traceId);
        }
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
